import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import { api } from '@/lib/apiService';

export async function GET(request) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }
    
    // 从URL中获取参数
    const { searchParams } = new URL(request.url);
    const name = searchParams.get('name');
    
    // 构建查询参数
    const queryParams = new URLSearchParams();
    if (name) queryParams.append('name', name);
    const qs = queryParams.toString();
    const endpoint = qs ? `templates?${qs}` : 'templates';

    // 直接使用当前会话中的token，避免在服务端再次获取session导致的循环依赖
    const accessToken = session.user?.accessToken;
    if (!accessToken) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }
    const response = await api.get(endpoint, {
      headers: { Authorization: `Bearer ${accessToken}` }
    });
    
    return NextResponse.json(response);
  } catch (error) {
    console.error('Database error:', error);
    const isUnauthorized = typeof error?.message === 'string' && error.message.includes('401');
    const status = isUnauthorized ? 401 : 500;
    return NextResponse.json({ error: error.message }, { status });
  }
}

export async function POST(request) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }
    
    const data = await request.json();
    
    // 调用Python后端的创建模板API - 使用带认证的方法
    const response = await api.auth.post('templates', data);
    
    return NextResponse.json(response);
  } catch (error) {
    console.error('Server error:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
